<template>
  <div class="layout-wrapper layout-witness">
    <div class="layout-header layout-search">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-button type="primary" @click="initDistrict()" :loading="btnLoading"> 区域初始化 </el-button>
        </el-form-item>
        <el-form-item class="rigthText">
<!--          <el-select
            v-model="searchForm.devicetype"
            class="ui-w320"
            option-max-width="180px"
            placeholder="设备类型"
            clearable
            @change="handleSearchFn()"
          >
            <el-option v-for="(value, key) in devicetype" :key="key" :label="value" :value="key" />
          </el-select>-->
          <el-input
            v-model.trim="searchForm.keywords"
            class="ui-w320"
            placeholder="区域/楼层名称"
            @keyup.native.enter="handleSearchFn()"
          >
            <el-button slot="append" type="primary" icon="icon-sousuo" @click="handleSearchFn()" />
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="layout-body">
      <el-table ref="taskTable" v-loading="tableLoading" :data="tableData" height="100%" stripe>
        <el-table-column type="index" align="left" label="序号" width="50">
          <template slot-scope="scope">
            {{ pageObj.currentPage * pageObj.pageSize + 1 + scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="区域名称" min-width="180" />
        <el-table-column prop="code" label="区域编号" min-width="120" />
        <el-table-column prop="floorname" label="楼层名称" min-width="120" />
        <el-table-column prop="funarea" :formatter="formatterFunarea" label="所属功能区" min-width="120" />
        <el-table-column
          prop="type"
          label="区域类型"
          min-width="120"
          :formatter="formatterType"
          show-overflow-tooltip
        />
        <el-table-column prop="personnum" label="容纳人数" min-width="130" />
        <el-table-column prop="area" label="区域面积" min-width="130" />
        <el-table-column prop="zwflag" :formatter="formatterZwflag" label="是否支持座位" min-width="130" />
        <el-table-column prop="districtdesc" label="区域描述说明" min-width="120" />
        <el-table-column
          prop="status"
          label="数据状态"
          min-width="120"
          :formatter="formatterStatus"
          show-overflow-tooltip
        />
<!--        <el-table-column label="操作" align="left" header-align="center" width="140">
          <template slot-scope="scope">
            <el-button type="text" size="default" @click="viewDate(scope.row)"> 查看 </el-button>
            <el-button type="text" size="default" @click="updateDate(scope.row)"> 修改 </el-button>
          </template>
        </el-table-column>-->
      </el-table>
    </div>
    <div class="layout-footer">
      <wpagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :pageSizes="pageObj.pageSizes"
        @pagination="projectListFn()"
      />
    </div>
    <!-- 编辑弹框 -->
    <el-dialog
      width="60%"
      :close-on-click-modal="false"
      draggable
      :show-close="false"
      title="区域信息"
      :visible.sync="editDevice"
    >
      <div>
        <el-form ref="districtForm" :model="districtForm" :rules="roomRules" label-width="auto">
          <el-form-item label="设备名称" prop="devicename">
            <el-input.0
              v-model="districtForm.devicename"
              placeholder="请输入设备名称"
              disabled
            />
          </el-form-item>
          <el-form-item label="设备编号" prop="devicecode">
            <el-input
              v-model="districtForm.devicecode"
              placeholder="请输入设备编号"
              disabled
            />
          </el-form-item>
          <el-form-item label="设备类型" prop="devicetype">
            <el-select
              v-model="districtForm.devicetype"
              style="width: 100%"
              filterable
              disabled
            >
              <el-option v-for="(value, key) in devicetype" :key="key" :label="value" :value="key" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备IP" prop="ip">
            <el-input
              v-model="districtForm.ip"
              placeholder="请输入设备IP"
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
          <el-form-item label="MAC地址" prop="devicemac">
            <el-input
              v-model="districtForm.devicemac"
              placeholder="请输入MAC地址"
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
          <el-form-item label="房间" prop="room.name">
            <el-input
              v-if="districtForm.room"
              v-model.lazy="districtForm.room.name"
              placeholder="请输入房间信息"
              disabled
            />
            <el-input
              v-else="districtForm.room"
              placeholder="请输入房间信息"
              disabled
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="childType != 'view'" :loading="btnLoading" type="primary" @click="submitData('districtForm')"
        >确定</el-button
        >
        <el-button @click="cancel('districtForm')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import { districtPage, deviceList, districtEdit, deviceQuery, initdistrict } from "../../../../../api/weeon/district";
export default {
  // 引入组件
  components: {},
  props: {},
  data() {
    // 这里存放数据
    return {
      childType: "",
      editDevice: false,
      btnLoading: false,
      searchForm: {
        devicetype: "",
        keywords: ""
      },
      districtType: {
        "BsDistrict":"房间",
        "PublicDistrict":"公共区域"
      },
      districtFunarea: {
        "BidOpening":"开标区",
        "BidEvaluation":"评标区",
        "PublicFunc":"公共服务区",
        "RestRoom":"专家休息室",
        "MeetingRoom":"会议室",
        "WitnessRoom":"见证室",
      },
      status: {
        "0":"无效",
        "1":"有效"
      },
      tableData: [],
      deviceData: [],
      tableLoading: false,
      pageObj: {
        total: 0,
        currentPage: 0,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      districtForm: {
        room:{name:""},
      },
      roomRules: {
        name: [{ required: true, message: "请输入房间名称", trigger: "blur" }],
        location: [{ required: true, message: "请输入房间位置", trigger: "blur" }],
        roomtype: [{ required: true, message: "请选择房间类型", trigger: "change" }]
      }
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.projectListFn();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 生命周期 - 销毁之前
  beforeDestroy() {},
  // 生命周期 - 销毁完成
  destroyed() {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
  // 方法集合
  methods: {
    // 搜索查询
    handleSearchFn() {
      this.pageObj.total = 0;
      this.pageObj.currentPage = 0;
      this.projectListFn();
    },
    // 数据列表
    async projectListFn() {
      try {
        this.tableLoading = true;
        this.tableData = [];
        console.log()
        let params = {
          // industryTypeList, // 行业类型
          // industryList,
          // tenderMode: this.searchForm.tenderMode,
          keywords: this.searchForm.keywords,
          pageNo: this.pageObj.currentPage,
          pageSize: this.pageObj.pageSize
        };
        const res = await districtPage(params);
        if (res.stat === 1) {
          if (res.data.totalElements === 0 && this.pageObj.currentPage !== 0) {
            this.pageObj.currentPage = 0;
            this.$nextTick(() => {
              this.projectListFn();
            });
            return;
          }

          this.tableData = res.data.content;
          console.log(this.tableData, "-------------------1");
          this.pageObj.total = res.data.totalElements;
          this.tableLoading = false;
        } else {
          this.tableLoading = false;
          this.$message({
            type: "error",
            message: res.msg || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (error) {
        console.log(error);
        this.tableLoading = false;
      }
    },

    //修改操作
    updateDate(row) {
      this.editDevice = true;
      this.districtForm = row;
      this.childType = "edit";
    },
    //查看操作
    viewDate(row) {
      // console.log("row"+row.room.name);
      this.editDevice = true;
      this.districtForm = row;
      this.childType = "view";
    },
    //取消
    cancel(formName) {
      this.editDevice = false;
      this.tableLoading = false;
      this.btnLoading = false;
      if (this.childType !== "view"){
        this.projectListFn();
      }
      this.childType = "";
    },
    //保存修改
    submitData(formName) {
      try {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.doEdit();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } catch (error) {
        console.error(error);
        this.$message({
          type: "warning",
          message: "获取数据失败，稍后再试"
        });
      }
    },
    //保存
    async doEdit() {
      this.btnLoading = true;
      delete this.districtForm.room;
      const res = await deviceEdit(this.districtForm);
      if (res.stat === 1) {
        this.$message({
          type: "success",
          message: "修改成功",
          single: true
        });
      } else {
        this.$message({
          type: "warning",
          message: res.msg,
          single: true
        });
      }
      this.btnLoading = false;
      this.editDevice = false;
      this.childType = "";
      this.deviceForm={room:{}}; //清空对象
      this.projectListFn(); //刷新列表
    },
    //初始化房间
    initDistrict(){
      this.$confirm("初始化区域会将当前的数据全部格式化，并重新加载，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.initDis();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            single: true
          });
        });
    },
    //初始化
    async initDis(){
      try {
        this.btnLoading = true;
        this.tableLoading = true;
        const res = await initdistrict();
        this.btnLoading = false;
        this.tableLoading = false;
        if (res.stat === 1) {
          this.$message({
            type: "success",
            message: "初始化成功",
            single: true
          });
          this.projectListFn();
        } else {
          this.$message({
            type: "error",
            message: res.msg || "初始化失败",
            single: true
          });
        }
      } catch (error) {
        console.error(error);
        this.btnLoading = false;
        this.tableLoading = false;
      }
    },
    //格式化设备类型
    formatterStatus(row, col, val){
      console.log(val);
      let str = "";
      if (val) {
        str = this.status[val];
      }
      return str;
    },
    //是否启用
    formatterType(row, col, val) {
      console.log(val);
      let str = "";
      if (val) {
        str = this.districtType[val];
      }
      return str;
    },
    //是否启用
    formatterFunarea(row, col, val) {
      console.log(val);
      let str = "";
      if (val) {
        str = this.districtFunarea[val];
      }
      return str;
    },
    //是否支持座位
    formatterZwflag(row, col, val) {
      console.log(val);
      let str = "";
      if (val == "0") {
        str = "不支持";
      } else if (val == "1") {
        str = "支持";
      }
      return str;
    },
    //修改设备状态
    updateDeviceenable(id, title, val){
      this.$confirm(title+"该设备，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.updateDevice(id, val);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
            single: true
          });
        });
    },
    async updateDevice(id, val){
      try {
        this.tableLoading = true;
        const res = await deviceEdit({id: id, deviceenable: val});
        this.tableLoading = false;
        if (res.stat === 1) {
          this.$message({
            type: "success",
            message: "操作成功",
            single: true
          });
          this.projectListFn();
        } else {
          this.$message({
            type: "error",
            message: res.msg || "操作失败",
            single: true
          });
        }
      } catch (error) {
        console.error("报错了---->"+error);
        this.tableLoading = false;
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.witness-result {
  width: 76px;
  height: 20px;
  line-height: 20px;
  background: #fc9306;
  border-radius: 10px;
  color: #fff;
  font-size: 12px;
  text-align: center;
}
.rigthText {
  padding-right: 10px;
  float: right;
  // margin-left: 460px !important;
}
.colorRed {
  color:red;
}
</style>
